/*
 * Copyright 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.android.apps.mytracks.services.sensors;

import static com.google.android.apps.mytracks.MyTracksConstants.TAG;

import com.google.android.apps.mytracks.content.Sensor;

import android.util.Log;
/**
 * An implementation of a SensorData parser for Polar HRM.
 * 
 * @author Joni Pakarinen
 */

public class PolarMessageParser implements MessageParser {

  @Override
  public Sensor.SensorDataSet parseBuffer(byte[] buffer) {

    StringBuilder sb = new StringBuilder();
    sb.append("Got polar data: ");
    for (int i = 0; i < buffer.length; i++) {
      sb.append(buffer[i] & 0xFF);
      if(i < buffer.length - 1){
        sb.append(',');
      }
    }
    Log.d(TAG, sb.toString());
    
    // Heart Rate
    Sensor.SensorData.Builder hr = Sensor.SensorData.newBuilder()
        .setValue(buffer[5] & 0xFF)
        .setState(Sensor.SensorState.SENDING);

    // This might be in the wrong place
    Log.d(TAG, "Battery: " + (buffer[4] & 0x60) + " %");
    

    return Sensor.SensorDataSet.newBuilder()
        .setCreationTime(System.currentTimeMillis())
        .setHeartRate(hr)
        .build();
    
  }

  @Override
  public boolean isValid(byte[] buffer) {

    return ((buffer[0] & 0xFF) == 254
        && (buffer[1] & 0xFF) + (buffer[2] & 0xFF) == 255
        && (buffer[3] & 0xFF) >= 0
        && (buffer[3] & 0xFF) <= 15
        && (buffer[5] & 0xFF) > 0);
      
  }

  @Override
  public int getFrameSize() {
    return 6;
  }
  
  @Override
  public int getBufferSize() {
    return 40;
  }

  @Override
  public int findNextAlignment(byte[] buffer) {
    return -1;
  }
}
